package com.itbaizhan;

import java.util.Arrays;

/**
 * 二分法查找
 */
public class TestBinarySearch02 {
    public static void main(String[] args) {
        int[] arr = {10,23,67,89,34,12,100,78,33,22,19};
        int searchWord02 = 22;
        //查找之前排序
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//数组打印用：Arrays.toString()
        System.out.println(searchWord02+"元素索引"+binarySearch02(arr,searchWord02));

    }
    public static int binarySearch02(int[] arr,int value02){ //value02 为要查找的数 ,不可以用void,因为没有返回值
        int low=0;
        int high= arr.length-1; //由0开始，所以-1
        while (low <= high){
            int middle = (low+high)/2;
            if( value02 == arr[middle]){
                return middle;
            }
            if (value02 < arr[middle]){
                high = arr[middle -1];
            }
            if(value02 > arr[middle]){
                low = arr[middle +1];
            }
        }
        return -1;

    }

}
